<?php
/**
 * 获取聊天信息
 */
namespace App\Service;

use App\Model\Msg;
use App\Model\UserBind;
use App\ServiceInterface;

class GetmsgService implements ServiceInterface
{
    private $_srever;

    private $_fd;

    private $_data;

    /**
     * BindService constructor.
     * @param null $server
     * @param int $fd
     * @param array $data
     */
    public function __construct($server=null,int $fd=0,array $data=[])
    {
        $this->_srever = $server;
        $this->_fd     = $fd;
        $this->_data   = $data;
    }

    /**
     * 参数校验
     * @return string
     */
    public function check():string
    {
        if (!isset($this->_data['action']) || empty($this->_data['action']))
        {
            return 'action is null';
        }

        return '';
    }

    /**
     * 具体逻辑
     * @return array
     */
    public function init():array
    {
        try {
            // 校验参数
            $check_str = $this->check();
            if ($check_str){
                throw new \Exception($check_str);
            }

            switch ($this->_data['action'])
            {
                case 'private':
                    $res_data = $this->privateMsg();
                    break;
                case 'friendMsg':
                    $res_data = $this->friendMsg();
                    break;
                case 'msgRead':
                    $res_data = $this->msgRead();
                    break;
                default:
                    $res_data = 'action is defind';
                    break;
            }

            if (!is_array($res_data))
                throw new \Exception($check_str);

            return [0, 'success', $res_data];

        }catch (\Exception $e){
            return [-1,$e->getMessage()];
        }
    }

    /**
     * @return array|string
     */
    private function privateMsg()
    {
        $this->msgRead();

        $info = Msg::getList($this->_data['appid'],$this->_data);

        if (isset($info['list']) && is_array($info['list']))
        {
            $info['list'] = array_reverse($info['list']);
        }

        return $info;
    }

    /**
     * 获取最近有聊天记录的好友及消息
     */
    private function friendMsg()
    {
        return Msg::getFriedMsg($this->_data['appid'], $this->_data);
    }

    private function msgRead()
    {
       return Msg::updateStatus($this->_data['appid'],$this->_data);
    }
}